﻿using System;
using System.Collections.Generic;
using System.Linq;
using LDSModel.Item;

namespace LDSModel.Dal
{
    public static class RecordService
    {
        public static IQueryable<RecordViewItem> Query(string oilId, string deviceId, DateTime startTime, DateTime endTime)
        {
            var oilFlag = string.IsNullOrWhiteSpace(oilId);
            var deviceFlag = string.IsNullOrWhiteSpace(deviceId);

            var oid = Guid.NewGuid();
            var did = Guid.NewGuid();

            if (!oilFlag) Guid.TryParse(oilId, out oid);
            if (!deviceFlag) Guid.TryParse(deviceId, out did);

            endTime = endTime.AddDays(1).AddSeconds(-1);

            var context = new DatabaseEntities();

            var result = from r in context.Data_Records
                         from d in context.Data_Device
                         from o in context.Data_OilTank
                         where r.DeviceID == d.DeviceId && d.OID == o.OId
                         && (oilFlag || o.OId == oid)
                         && (deviceFlag || d.DeviceId == did)
                         && r.AlarmTime >= startTime && r.AlarmTime < endTime
                         orderby r.AlarmTime descending
                         select new RecordViewItem
                             {
                                 OilName = o.Name,
                                 DeviceName = d.Name,
                                 AlarmCount = r.AlarmCount,
                                 AlarmTime = r.AlarmTime,
                                 AValue = r.CH1Value,
                                 BValue = r.CH2Value
                             };

            return result;
        }

        public static List<Data_Records> Query(Guid deviceId, DateTime startTime, DateTime endTime)
        {
            var context = new DatabaseEntities();

            var result = new List<Data_Records>((from r in context.Data_Records
                                                 where r.DeviceID == deviceId
                                                 && r.AlarmTime >= startTime && r.AlarmTime < endTime
                                                 orderby r.AlarmTime
                                                 select r).ToArray());

            return result;
        }
    }
}
